package com.shijianchen.interceptor;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.shijianchen.utils.BaseControllerUtil;
import com.shijianchen.utils.Result;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Enumeration;

@Component
public class AuthInterceptor implements HandlerInterceptor {
    private void printEntity(Object entity,HttpServletResponse response) throws IOException {
        response.setContentType("application/json");
        response.setCharacterEncoding("UTF-8");
        ObjectMapper mapper = new ObjectMapper();
        PrintWriter writer = response.getWriter();
        writer.write(mapper.writeValueAsString(entity));
        writer.close();
    }
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("Authorization");
        if(token == null){
            Result<Object> fail = Result.fail("请求头不存在token，请检查代码");
            printEntity(fail,response);
            return false;
        }
        Claims userInfo = BaseControllerUtil.getUserInfo(token);
        if (userInfo == null){
            Result<Object> fail = Result.fail("用户无登录权限");
            printEntity(fail,response);
            return false;
        }
        return true;
    }
}
